package com.RateLimiter;

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.*;
import java.util.stream.IntStream;

import static java.lang.Thread.currentThread;

/**
 * Created by Lxk on 2019/4/28.
 */
public class BucketRateLimiter {

    private final static RateLimiter limiter = RateLimiter.create(10);

    private final static Semaphore semaphore = new Semaphore(5);

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(10);
        IntStream.range(0,100).forEach(i -> service.submit(BucketRateLimiter::testSemaphore));
    }

    private static void testLimiter(){
        System.out.println(currentThread() + " waiting : " + limiter.acquire());
    }

    private static void testSemaphore(){
        try{
            semaphore.acquire();
            System.out.println(currentThread() + " is coming and do work.");
            TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(10));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            semaphore.release();
            System.out.println(currentThread() + " is done and release.");
        }
    }

}
